package com.grace.dao;

import com.grace.entity.Student;
import com.grace.util.Hibernate.HibernateTemplate;

import java.util.List;

public class StudentDaoImpl implements StudentDao {

    @Override
    public Student selectStudent(Long id) {
        return (Student) HibernateTemplate.execute(ses -> ses.get(Student.class, id));
    }

    @Override
    public Student selectStudent(String sno, String pwd) {
        return (Student) HibernateTemplate.execute(ses -> ses.createQuery("from Student where sno=:sno and pwd=:pwd")
                .setParameter("sno", sno)
                .setParameter("pwd", pwd).uniqueResult());
    }

    @Override
    public void insert(Student student) {
        HibernateTemplate.execute(ses -> ses.save(student));
    }

    @Override
    public List<Student> getPageStudents(int pageNo, int pageSize) {
        return (List<Student>) HibernateTemplate.execute(ses -> ses.createQuery("from Student")
                .setFirstResult((pageNo - 1) * pageSize)
                .setMaxResults(pageSize).list());
    }

    @Override
    public long getCount() {
        return (long) HibernateTemplate.execute(ses -> ses.createQuery("select count(id) from Student").uniqueResult());
    }

    @Override
    public void deleteStudent(Student student) {
        HibernateTemplate.execute(ses -> {
            ses.delete(student);
            return null;
        });

    }

    @Override
    public void update(Student student) {
        HibernateTemplate.execute(ses -> {
            ses.update(student);
            return null;
        });
    }
}
